package cn.wolfcode.util;

import cn.wolfcode.domain.LogManage;
import cn.wolfcode.exception.LoginException;
import cn.wolfcode.qo.UserContext;
import cn.wolfcode.service.ILogManageService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component //把当前类注入到spring容器中
@Aspect    //把当前类标识为一个切面供容器读取
public class AopConfig {

    @Autowired
    private ILogManageService logManageService;
    @Autowired
    private HttpServletRequest request;
    /**
     * 指定切入点
     * 对贴有自定义注解@RequiredPermission的方法，进行切面
     */
    @Pointcut("@annotation(cn.wolfcode.util.RequiredPermission)")
    private void useMethod() {
    }

    /**
     * 对切入点进行增强
     */
    @Around(value = "useMethod()")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //执行处理方法（执行控制器中的方法）
        Object result = null;
        //获取检测前的时间
        Long startTime = System.currentTimeMillis();

        //获取当前用户的名字
        String username = UserContext.getEmployee().getUsername();

        //获取method方法
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();

        //获取请求方法的请求参数
        String queryString = request.getQueryString();


        //获取注解上面的数据
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);

        //用户操作
        String name = annotation.name();
        //请求方法
        String expression = annotation.expression();

        //通过ipUtil的方法获取当前ip地址
        String ip = IPUtil.getIp(request);

        //获取操作时间就是当前时间
        Date date = new Date();

        //创建日志对象
        LogManage logManage = new LogManage();
        logManage.setArgs(queryString);
        logManage.setDatatime(date);
        logManage.setExpression(expression);
        logManage.setIp(ip);
        logManage.setUsername(username);
        logManage.setName(name);
        try {
            result = proceedingJoinPoint.proceed();
            logManage.setResult(true);
            logManage.setErrormessage("无");
        } catch (Throwable e) {
            logManage.setResult(false);
            logManage.setErrormessage(e.getMessage());
            //把异常信息存到数据库表中
            //再把异常抛出去给统一异常处理 和 自定义异常处理
            //如果是LoginException
            if(e instanceof LoginException){
                //这个类型就抛给自定义异常
                throw  new LoginException(e.getMessage());
            }else {
                throw  new Exception(e.getMessage());
            }
            //如果不抛出去就相当于做了处理 但是catch后获取完信息在抛出去就相当于没抛出去
        } finally {
            //获取检测后的时间
            Long endTime = System.currentTimeMillis();
            //执行毫秒值
            Long time = endTime - startTime;
            logManage.setExecution(time);
            logManageService.save(logManage);
        }
        //result是方法的返回值，直接return回去就会返回给springmvc处理
        return result;
    }


}